package pkg

import (
	"config-client-v1/utils/tools"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"runtime/debug"
	"strconv"
	"strings"
)

func LoadingFSE(fseID string) (fse *FSEquip) {
	fse = &FSEquip{}
	str, err := tools.ReadFileContent("fse-" + fseID + ".json")
	if err != nil {
		fmt.Println("加载设备信息失败:", err)
		return
	}
	err = json.Unmarshal([]byte(str), &fse)
	if err != nil {
		fmt.Println("解析设备信息失败:", err)
		return
	}
	fse.CalculateDataScale()
	fmt.Printf("设备信息: %s %s:%d\n", fse.Name, fse.IP, fse.Port)
	fmt.Printf("数据规模: AI=%d, DI=%d, AQ=%d, DQ=%d, Other=%d, EData=%d, 泵组电磁阀=%d, 增压泵电磁阀=%d, 压力电磁阀=%d\n",
		fse.DS.AI, fse.DS.DI, fse.DS.AQ, fse.DS.DQ, fse.DS.Other, fse.DS.EData, fse.DS.Bengzu, fse.DS.Zengya, fse.DS.Pressure)
	for _, row := range fse.FSModule {
		switch row.ModuleType {
		case "泵组电磁阀":
			row.BengzuModel = &BengzuModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), row.BengzuModel)
			if err != nil {
				fmt.Printf("WARNING 解析泵组电磁阀失败:%s\n", err)
				continue
			}
		case "增压泵电磁阀":
			row.ZengyaModel = &ZengyaModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), row.ZengyaModel)
			if err != nil {
				fmt.Printf("WARNING 解析增压泵电磁阀失败:%s\n", err)
				continue
			}
		case "压力电磁阀":
			row.PressureSVModel = &PressureSVModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), row.PressureSVModel)
			if err != nil {
				fmt.Printf("WARNING 解析压力电磁阀失败:%s\n", err)
				continue
			}
		}
		row.JsonDetail = "{}"
	}
	return fse
}

func FixDataLength(data []byte) {
	length := len(data)
	lengthBytes := tools.Uint16ToBytes(uint16(length), "big")
	data[3] = lengthBytes[0]
	data[4] = lengthBytes[1]
}

// CalculateDataScale 统计FS设备模块数量
func (fse *FSEquip) CalculateDataScale() {
	ds := &DataScale{}
	for _, module := range fse.FSModule {
		if module.ModuleType == "AI" {
			ds.AI++
		}
		if module.ModuleType == "AQ" {
			ds.AQ++
		}
		if module.ModuleType == "DI" {
			ds.DI++
		}
		if module.ModuleType == "DQ" {
			ds.DQ++
		}
		if module.ModuleType == "Other" {
			ds.Other++
		}
		if module.ModuleType == "泵组电磁阀" {
			ds.Bengzu++
		}
		if module.ModuleType == "增压泵电磁阀" {
			ds.Zengya++
		}
		if module.ModuleType == "电调阀" {
			ds.Diantiao++
		}
		if module.ModuleType == "压力电磁阀" {
			ds.Pressure++
		}
		if module.ModuleType == "电源控制" {
			ds.Power++
		}
		if module.ModuleType == "电源状态" {
			ds.PowerState++
		}
		if module.ModuleType == "模态采集" {
			ds.ModeCollect++
		}
		if module.ModuleType == "故障诊断" {
			ds.Diag++
		}
	}
	fse.DS = ds
}

func RandFloat32Bytes(min, max int) (b [4]byte) {
	r := tools.GetRandAreaNumber(min, max)
	f := float32(r) / 100.0
	res := tools.Float32ToBytes(f, "little")
	if len(res) != 4 {
		return
	}
	b[0] = res[0]
	b[1] = res[1]
	b[2] = res[2]
	b[3] = res[3]
	return
}
func RandInt32Bytes(min, max int) (b [4]byte) {
	r := tools.GetRandAreaNumber(min, max)
	v := uint32(r)
	b = tools.Uint32ToBytes(v, "big")
	return
}
func RandInt16Bytes(min, max int) (b [2]byte) {
	r := tools.GetRandAreaNumber(min, max)
	v := uint16(r)
	b = tools.Uint16ToBytes(v, "big")
	return
}

func Ip2Bytes(ip string) (b []byte) {
	b = make([]byte, 4)
	ipArr := strings.Split(ip, ".")
	if len(ipArr) != 4 {
		return
	}
	for i := 0; i < 4; i++ {
		n, _ := strconv.Atoi(ipArr[i])
		b[i] = byte(n)
	}
	return
}
func IsValidIP(ipStr string) bool {
	ip := net.ParseIP(ipStr)
	return ip != nil
}

// GenFSFrameData0102 IP读取正常返回
func GenFSFrameData0102(ip1, ip2 string, port1, port2 uint16, param1, param2, param3 float64, redundantEnable uint8) (data []byte, err error) {
	if !IsValidIP(ip1) || !IsValidIP(ip2) {
		err = errors.New("ip地址不合法")
		return
	}
	ip1Bytes := Ip2Bytes(ip1)
	port1Bytes := tools.Uint16ToBytes(port1, "big")

	ip2Bytes := Ip2Bytes(ip2)
	port2Bytes := tools.Uint16ToBytes(port2, "big")

	param1Bytes := tools.Float32ToBytes(float32(param1), "little")
	param2Bytes := tools.Float32ToBytes(float32(param2), "little")
	param3Bytes := tools.Float32ToBytes(float32(param3), "little")

	data = []byte{0x5A, 0x01, 0x02, 0x00, 0x24, 0x01, 0x01}

	if redundantEnable == 1 { // 冗余开闭 1011=0B, 1100=0C
		data = append(data, 0x0C)
	} else {
		data = append(data, 0x0B)
	}
	data = append(data, ip1Bytes...)       // IP1
	data = append(data, port1Bytes[0:]...) // PORT1
	data = append(data, ip2Bytes...)       // IP2
	data = append(data, port2Bytes[0:]...) // PORT2

	data = append(data, param1Bytes...)               // 参数1 float32
	data = append(data, param2Bytes...)               // 参数1 float32
	data = append(data, param3Bytes...)               // 参数1 float32
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}

// GenFSFrameData0401 FS基本信息读取正常返回
func GenFSFrameData0401(ds *DataScale) (data []byte) {
	data = []byte{0x5A, 0x04, 0x01, 0x00, 0x0C, 0x01, 0x01}
	data = append(data, ds.AI, ds.AQ, ds.DI, ds.DQ, ds.Other)
	edataBytes := tools.Uint16ToBytes(ds.EData, "big")
	data = append(data, edataBytes[:]...)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}

func getAIAQContentBytes(fse *FSEquip, moduleType string, moduleNumber uint8) (contentBytes []byte, channelQuantity uint8) {
	contentBytes = make([]byte, 0) // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == moduleType && row.Code3 == fmt.Sprintf("%02d", moduleNumber) {
			for _, item := range row.FrameItem {
				channelQuantity++
				upperLimitValue := tools.Float32ToBytes(float32(item.UpperLimitValue), "little")
				lowerLimitValue := tools.Float32ToBytes(float32(item.LowerLimitValue), "little")
				upper2LimitValue := tools.Float32ToBytes(float32(item.Upper2LimitValue), "little")
				lower2LimitValue := tools.Float32ToBytes(float32(item.Lower2LimitValue), "little")
				rangeUpperLimit := tools.Float32ToBytes(float32(item.RangeUpperLimit), "little")
				rangeLowerLimit := tools.Float32ToBytes(float32(item.RangeLowerLimit), "little")
				contentBytes = append(contentBytes, upperLimitValue...)
				contentBytes = append(contentBytes, lowerLimitValue...)
				contentBytes = append(contentBytes, upper2LimitValue...)
				contentBytes = append(contentBytes, lower2LimitValue...)
				contentBytes = append(contentBytes, rangeUpperLimit...)
				contentBytes = append(contentBytes, rangeLowerLimit...)
				contentBytes = append(contentBytes, item.Shield)
				contentBytes = append(contentBytes, item.AlertBit)
				contentBytes = append(contentBytes, item.Formula)
				contentBytes = append(contentBytes, item.DiagMode)
			}
		}
	}
	return
}
func getDIDQContentBytes(fse *FSEquip, moduleType string, moduleNumber uint8) (contentBytes []byte, channelQuantity uint8) {
	contentBytes = make([]byte, 0) // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == moduleType && row.Code3 == fmt.Sprintf("%02d", moduleNumber) {
			for _, item := range row.FrameItem {
				channelQuantity++
				shieldTime := tools.Uint16ToBytes(uint16(item.ShieldTime), "big")
				contentBytes = append(contentBytes, item.Shield)
				contentBytes = append(contentBytes, shieldTime[:]...)
			}
		}
	}
	return
}
func getOtherContentBytes(fse *FSEquip, moduleType string, moduleNumber uint8) (contentBytes []byte, channelQuantity uint8) {
	fmt.Printf("开始生成 Other 帧内容\n")
	contentBytes = make([]byte, 0) // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == moduleType && row.Code3 == fmt.Sprintf("%02d", moduleNumber) {
			fmt.Printf("Other 模块: %s ,len(row.FrameItem)=%d\n", row.ModuleName, len(row.FrameItem))
			for _, item := range row.FrameItem {
				channelQuantity++
				if item.ChannelType == "AI" || item.ChannelType == "AQ" {
					if item.ChannelType == "AI" {
						contentBytes = append(contentBytes, 0x01)
					}
					if item.ChannelType == "AQ" {
						contentBytes = append(contentBytes, 0x02)
					}
					upperLimitValue := tools.Float32ToBytes(float32(item.UpperLimitValue), "little")
					lowerLimitValue := tools.Float32ToBytes(float32(item.LowerLimitValue), "little")
					upper2LimitValue := tools.Float32ToBytes(float32(item.Upper2LimitValue), "little")
					lower2LimitValue := tools.Float32ToBytes(float32(item.Lower2LimitValue), "little")
					rangeUpperLimit := tools.Float32ToBytes(float32(item.RangeUpperLimit), "little")
					rangeLowerLimit := tools.Float32ToBytes(float32(item.RangeLowerLimit), "little")
					contentBytes = append(contentBytes, upperLimitValue...)
					contentBytes = append(contentBytes, lowerLimitValue...)
					contentBytes = append(contentBytes, upper2LimitValue...)
					contentBytes = append(contentBytes, lower2LimitValue...)
					contentBytes = append(contentBytes, rangeUpperLimit...)
					contentBytes = append(contentBytes, rangeLowerLimit...)
					contentBytes = append(contentBytes, item.Shield)
					contentBytes = append(contentBytes, item.AlertBit)
					contentBytes = append(contentBytes, item.Formula)
					contentBytes = append(contentBytes, item.DiagMode)
				} else if item.ChannelType == "DI" || item.ChannelType == "DQ" {
					fmt.Printf("code4=%s, item.ModuleType = %s\n", item.Code4, item.ChannelType)
					if item.ChannelType == "DI" {
						contentBytes = append(contentBytes, 0x03)
					}
					if item.ChannelType == "DQ" {
						contentBytes = append(contentBytes, 0x04)
					}
					fmt.Printf("len=%d ,v=%d\n", len(contentBytes), contentBytes[len(contentBytes)-1])
					shieldTime := tools.Uint16ToBytes(uint16(item.ShieldTime), "big")
					contentBytes = append(contentBytes, item.Shield)
					contentBytes = append(contentBytes, shieldTime[:]...)
				} else {
					fmt.Println("!!!!!! 不应该出现这里, Other模块下的通道类型异常")
				}
			}
		}
	}
	return
}

// GenFSFrameData04 模块上载正常返回
func GenFSFrameData04(fse *FSEquip, cmdCode uint8, moduleNumber uint8) (data []byte, err error) {
	data = []byte{0x5A, 0x04, cmdCode, 0x00, 0x0C, 0x01, 0x01}
	var moduleQuantity, channelQuantity uint8
	contentBytes := make([]byte, 0) // 内容部分
	switch cmdCode {
	case 0x02:
		moduleQuantity = fse.DS.AI
		contentBytes, channelQuantity = getAIAQContentBytes(fse, "AI", moduleNumber)
	case 0x03:
		moduleQuantity = fse.DS.AQ
		contentBytes, channelQuantity = getAIAQContentBytes(fse, "AQ", moduleNumber)
	case 0x04:
		moduleQuantity = fse.DS.DI
		contentBytes, channelQuantity = getDIDQContentBytes(fse, "DI", moduleNumber)
	case 0x05:
		moduleQuantity = fse.DS.DQ
		contentBytes, channelQuantity = getDIDQContentBytes(fse, "DQ", moduleNumber)
	case 0x06:
		moduleQuantity = fse.DS.Other
		contentBytes, channelQuantity = getOtherContentBytes(fse, "Other", moduleNumber)
	default:
		err = errors.New(fmt.Sprintf("GenFSFrameData04%02d 命令异常", cmdCode))
		return
	}
	if len(contentBytes) == 0 {
		err = errors.New(fmt.Sprintf("GenFSFrameData04%02d 设备数据异常", cmdCode))
		return
	}
	data = append(data, moduleQuantity, moduleNumber, channelQuantity)
	data = append(data, contentBytes...)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSFrameData0601(ds *DataScale) (data []byte) {
	data = []byte{0x5A, 0x06, 0x01, 0xFF, 0xFF, 0x01, 0x01}
	data = append(data, ds.AI, ds.DI, ds.AQ, ds.DQ, ds.Other)
	edataBytes := tools.Uint16ToBytes(ds.EData, "big")
	data = append(data, edataBytes[:]...)
	data = append(data, ds.Bengzu, ds.Zengya, ds.Pressure)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSFrameData0602(fse *FSEquip) (data []byte, err error) {
	ds := fse.DS
	data = []byte{0x5A, 0x06, 0x02, 0xEE, 0xEE, 0x01, 0x01}
	data = append(data, ds.AI, ds.DI, ds.AQ, ds.DQ, ds.Other)
	edataBytes := tools.Uint16ToBytes(ds.EData, "big")
	data = append(data, edataBytes[:]...)
	data = append(data, ds.Bengzu, ds.Zengya, ds.Pressure)
	contentBytes := make([]byte, 0)
	for _, row := range fse.FSModule {
		if row.ModuleType == "AI" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))       // 模块地址
			contentBytes = append(contentBytes, byte(len(row.FrameItem))) // 模块通道数
			for _, item := range row.FrameItem {
				var value [4]byte
				if RandomCode4[item.Code4] {
					value = RandFloat32Bytes(8000, 9999) // 模拟数据
				} else {
					value = tools.Float32ToBytes4(float32(item.Value), "little")
				}
				if item.Addr == "00-00-01-008" {
					fmt.Printf("addr=%s,value=%v,bytes=%v\n", item.Addr, item.Value, value)
				}
				contentBytes = append(contentBytes, value[:]...)
				contentBytes = append(contentBytes, item.Shield)
				contentBytes = append(contentBytes, item.AlertBit)
			}
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "AQ" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))       // 模块地址
			contentBytes = append(contentBytes, byte(len(row.FrameItem))) // 模块通道数
			for _, item := range row.FrameItem {
				var value [4]byte
				if RandomCode4[item.Code4] {
					value = RandFloat32Bytes(10000, 12000) // 模拟数据
				} else {
					value = tools.Float32ToBytes4(float32(item.Value), "little")
				}
				contentBytes = append(contentBytes, value[:]...)
				contentBytes = append(contentBytes, item.Shield)
				contentBytes = append(contentBytes, item.AlertBit)
			}
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "DI" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))       // 模块地址
			contentBytes = append(contentBytes, byte(len(row.FrameItem))) // 模块通道数
			for _, item := range row.FrameItem {
				contentBytes = append(contentBytes, byte(item.Value))
			}
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "DQ" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))       // 模块地址
			contentBytes = append(contentBytes, byte(len(row.FrameItem))) // 模块通道数
			for _, item := range row.FrameItem {
				contentBytes = append(contentBytes, byte(item.Value))
			}
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "Other" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))       // 模块地址
			contentBytes = append(contentBytes, byte(len(row.FrameItem))) // 模块通道数

			for _, item := range row.FrameItem {
				if item.ChannelType == "AI" {
					contentBytes = append(contentBytes, 0x01) // 通道类型
					var value [4]byte
					if RandomCode4[item.Code4] {
						value = RandFloat32Bytes(1800, 3000) // 模拟数据
					} else {
						value = tools.Float32ToBytes4(float32(item.Value), "little")
					}
					contentBytes = append(contentBytes, value[:]...)
					contentBytes = append(contentBytes, item.Shield)
					contentBytes = append(contentBytes, item.AlertBit)
				}
				if item.ChannelType == "AQ" {
					contentBytes = append(contentBytes, 0x02) // 通道类型
					var value [4]byte
					if RandomCode4[item.Code4] {
						value = RandFloat32Bytes(3000, 4500) // 模拟数据
					} else {
						value = tools.Float32ToBytes4(float32(item.Value), "little")
					}
					contentBytes = append(contentBytes, value[:]...)
					contentBytes = append(contentBytes, item.Shield)
					contentBytes = append(contentBytes, item.AlertBit)
				}
				if item.ChannelType == "DI" {
					contentBytes = append(contentBytes, 0x03) // 通道类型
					contentBytes = append(contentBytes, byte(item.Value))
				}
				if item.ChannelType == "DQ" {
					contentBytes = append(contentBytes, 0x04) // 通道类型
					contentBytes = append(contentBytes, byte(item.Value))
				}
			}
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "泵组电磁阀" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))                      // 模型序号
			contentBytes = append(contentBytes, row.BengzuModel.BengzuStartControlValue) // 开控制
			contentBytes = append(contentBytes, row.BengzuModel.BengzuStopControlValue)  // 关控制
			contentBytes = append(contentBytes, row.BengzuModel.BengzuStartStateValue)   // 开状态
			contentBytes = append(contentBytes, row.BengzuModel.BengzuStopStateValue)    // 关状态
			contentBytes = append(contentBytes, row.BengzuModel.LiansuoValue)            // 连锁

		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "增压泵电磁阀" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))           // 模型序号
			contentBytes = append(contentBytes, row.ZengyaModel.LiansuoValue) // 连锁
		}
	}
	for _, row := range fse.FSModule {
		if row.ModuleType == "压力电磁阀" {
			moduleNumber, _ := strconv.Atoi(row.Code3)
			contentBytes = append(contentBytes, byte(moduleNumber))               // 模型序号
			contentBytes = append(contentBytes, row.PressureSVModel.LiansuoValue) // 连锁
		}
	}
	data = append(data, contentBytes...)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSFrameData0603(fse *FSEquip) (data []byte, err error) {
	data, err = GenFSFrameData0602(fse)
	if err != nil {
		return
	}
	data[2] = 0x03
	return
}
func GenFSFrameData0604(fse *FSEquip) (data []byte, err error) {
	data, err = GenFSFrameData0602(fse)
	if err != nil {
		return
	}
	data[2] = 0x04
	return
}
func Addr2Bytes(addr string) (b []byte) {
	b = make([]byte, 2)
	b[0] = 0
	b[1] = 0
	arr := strings.Split(addr, "-")
	if len(arr) != 4 {
		return
	}
	code3, _ := strconv.Atoi(arr[2])
	code4, _ := strconv.Atoi(arr[3])
	b[0] = byte(code3)
	b[1] = byte(code4)
	return
}

// GenFSFrameData0501 模型控制信息读取正常返回
func GenFSFrameData0501(ds *DataScale) (data []byte) {
	data = []byte{0x5A, 0x05, 0x01, 0x00, 0x0C, 0x01, 0x01}
	data = append(data, ds.Bengzu, ds.Zengya, ds.Diantiao, ds.Pressure, ds.Power, ds.PowerState, ds.ModeCollect, ds.Diag)
	edataBytes := tools.Uint16ToBytes(ds.EData, "big")
	data = append(data, edataBytes[:]...)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0502(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x02, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "泵组电磁阀" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x01)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "泵组电磁阀" && row.Code3 == code3 {
			contentModel := BengzuModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			/*--- 泵组控制 ---*/
			// todo 1. 直接使用模型字段的预设值 2. 使用模型字段的变量地址的当前值 3. 增加一个字段是否使用预设值, 如果勾选则直接使用预设值, 如果未勾选则去找到变量当前值
			data = append(data, contentModel.BengzuStartControlValue)
			data = append(data, contentModel.BengzuStopControlValue)
			data = append(data, contentModel.BengzuStartStateValue)
			data = append(data, contentModel.BengzuStopStateValue)
			data = append(data, contentModel.LiansuoValue)
			data = append(data, contentModel.RemoteLocalValue)
			data = append(data, contentModel.ControlMethodValue)
			data = append(data, tools.Float32ToBytes(float32(contentModel.BengzuParam1Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.BengzuParam2Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.BengzuParam3Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.BengzuParam4Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.BengzuParam5Value), "little")...)

			data = append(data, 0x02) // 外部变量

			data = append(data, Addr2Bytes(contentModel.BengqianPressure)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStartControl)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStopControl)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStartState)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStopState)...)

			data = append(data, Addr2Bytes(contentModel.QianjibengStartControl)...)
			data = append(data, Addr2Bytes(contentModel.QianjibengStopControl)...)
			data = append(data, Addr2Bytes(contentModel.QianjibengStartState)...)
			data = append(data, Addr2Bytes(contentModel.QianjibengStopState)...)

			data = append(data, Addr2Bytes(contentModel.LuocibengStartControl)...)
			data = append(data, Addr2Bytes(contentModel.LuocibengStopControl)...)
			data = append(data, Addr2Bytes(contentModel.LuocibengStartState)...)
			data = append(data, Addr2Bytes(contentModel.LuocibengStopState)...)

			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0503(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x03, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "增压泵电磁阀" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x01)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "增压泵电磁阀" && row.Code3 == code3 {
			contentModel := ZengyaModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, contentModel.LiansuoValue)
			data = append(data, contentModel.RemoteLocalValue)
			data = append(data, contentModel.ControlMethodValue)

			data = append(data, 0x02) // 外部模块量
			data = append(data, Addr2Bytes(contentModel.BengqianPressure)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStartControl)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStopControl)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStartState)...)
			data = append(data, Addr2Bytes(contentModel.BengqianStopState)...)

			data = append(data, Addr2Bytes(contentModel.ZengyaStartControl)...)
			data = append(data, Addr2Bytes(contentModel.ZengyaStopControl)...)
			data = append(data, Addr2Bytes(contentModel.ZengyaStartState)...)
			data = append(data, Addr2Bytes(contentModel.ZengyaStopState)...)
			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0504(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x04, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "电调阀" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x02)                            // 外部模块量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "电调阀" && row.Code3 == code3 {
			contentModel := DiantiaoSVModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, Addr2Bytes(contentModel.CurrentKaidu)...)
			data = append(data, Addr2Bytes(contentModel.SetKaidu)...)
			data = append(data, Addr2Bytes(contentModel.Control)...)
			data = append(data, Addr2Bytes(contentModel.SetStep)...)
			data = append(data, Addr2Bytes(contentModel.SelfInspection)...)

			data = append(data, Addr2Bytes(contentModel.Up)...)
			data = append(data, Addr2Bytes(contentModel.Down)...)
			data = append(data, Addr2Bytes(contentModel.AllOn)...)
			data = append(data, Addr2Bytes(contentModel.AllOff)...)
			data = append(data, Addr2Bytes(contentModel.AllOnState)...)
			data = append(data, Addr2Bytes(contentModel.AllOffState)...)
			data = append(data, Addr2Bytes(contentModel.QianjiPressure)...)
			data = append(data, Addr2Bytes(contentModel.HoujiPressure)...)
			data = append(data, Addr2Bytes(contentModel.DestPressure)...)

			data = append(data, Addr2Bytes(contentModel.P)...)
			data = append(data, Addr2Bytes(contentModel.I)...)
			data = append(data, Addr2Bytes(contentModel.D)...)

			data = append(data, Addr2Bytes(contentModel.CustomStartControl)...)
			data = append(data, Addr2Bytes(contentModel.CustomStopControl)...)
			data = append(data, Addr2Bytes(contentModel.CustomStartState)...)
			data = append(data, Addr2Bytes(contentModel.CustomStopState)...)
			data = append(data, Addr2Bytes(contentModel.PID)...)
			data = append(data, Addr2Bytes(contentModel.RemoteLocal)...)
			data = append(data, Addr2Bytes(contentModel.ControlMethod)...)
			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}

func GenFSModuleData0505(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x05, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "压力电磁阀" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x01)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "压力电磁阀" && row.Code3 == code3 {
			contentModel := PressureSVModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, contentModel.LiansuoValue)
			data = append(data, contentModel.ControlMethodValue)

			data = append(data, 0x02) // 外部模块量
			data = append(data, Addr2Bytes(contentModel.Pressure)...)
			data = append(data, Addr2Bytes(contentModel.SVStartControl)...)
			data = append(data, Addr2Bytes(contentModel.SVStopControl)...)
			data = append(data, Addr2Bytes(contentModel.SVStartState)...)
			data = append(data, Addr2Bytes(contentModel.SVStopState)...)

			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0506(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x06, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "电源控制" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x03)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "电源控制" && row.Code3 == code3 {
			contentModel := PowerModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.U1Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.U2Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.U3Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.I1Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.I2Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.I3Value), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.FValue), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.ActivePowerValue), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.ReactivePowerValue), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.ApparentPowerValue), "little")...)

			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0507(fse *FSEquip, code3 string) (data []byte, err error) {
	//fmt.Printf("电源状态模型 code3 =%s\n", code3)
	data = []byte{0x5A, 0x05, 0x07, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "电源状态" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x03)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "电源状态" && row.Code3 == code3 {
			contentModel := PowerStateModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.RunningStateValue), "little")...)
			data = append(data, 0x01) // real 类型
			data = append(data, tools.Float32ToBytes(float32(contentModel.ErrorStateValue), "little")...)
			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0508(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x08, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "模态采集" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x02)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "模态采集" && row.Code3 == code3 {
			contentModel := ModeCollectModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, Addr2Bytes(contentModel.StimulatePoint)...)
			data = append(data, Addr2Bytes(contentModel.ResponsePoint)...)
			data = append(data, Addr2Bytes(contentModel.StartControl)...)
			data = append(data, Addr2Bytes(contentModel.StopControl)...)
			data = append(data, Addr2Bytes(contentModel.StartState)...)
			data = append(data, Addr2Bytes(contentModel.StopState)...)

			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}
func GenFSModuleData0509(fse *FSEquip, code3 string) (data []byte, err error) {
	data = []byte{0x5A, 0x05, 0x09, 0x00, 0x24}
	ModelNum := 0                       // 模型总数
	ModelCode, _ := strconv.Atoi(code3) // 模型序号
	contentBytes := make([]byte, 0)     // 内容部分
	for _, row := range fse.FSModule {
		if row.ModuleType == "故障诊断" {
			ModelNum++
		}
	}
	data = append(data, byte(ModelNum), byte(ModelCode)) // 模型总数和序号
	data = append(data, 0x01)                            // 内部变量
	found := false
	for _, row := range fse.FSModule {
		if row.ModuleType == "故障诊断" && row.Code3 == code3 {
			contentModel := DiagModel{}
			err = json.Unmarshal([]byte(row.JsonDetail), &contentModel)
			if err != nil {
				return
			}
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagModeValue), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagParam1Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagParam2Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagParam3Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagParam4Value), "little")...)
			data = append(data, tools.Float32ToBytes(float32(contentModel.DiagParam5Value), "little")...)
			found = true
			break
		}
	}
	if !found {
		err = errors.New("未找到当前模型数据")
		return
	}
	// 内容部分
	data = append(data, contentBytes...)
	// 尾部
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xA5) // 状态,保留,帧尾
	FixDataLength(data)
	return
}

func Response0602(fse *FSEquip, client *Client) (err error) {
	defer func() {
		if err0 := recover(); err0 != nil {
			fmt.Println("Response0602 Error: ", err0)
			debug.PrintStack()
		}
	}()
	respData, err := GenFSFrameData0602(fse)
	if err != nil {
		err = errors.New("pkg.GenFSFrameData0602 失败")
		return
	}
	cmdCode := respData[2]
	var n int
	dataScaleBytes := respData[7:17]           // 数据规模部分
	dataPart := respData[17 : len(respData)-5] // 数据内容部分
	frameQuantity := len(dataPart) / 1200      // 数据内容分成几帧
	frameTail := len(dataPart) % 1200          // 余数
	fmt.Printf("数据部分总长度=%d\n", len(dataPart))
	//fmt.Printf("data=%s\n", tools.ByteArrayToHexStr(dataPart))
	if frameQuantity == 0 || (frameQuantity == 1 && frameTail == 0) {
		// 只有1帧的情况
		respData[5] = 1
		respData[6] = 1
		_, err = client.Connection.Write(respData)
		if err != nil {
			err = errors.New("0602 TCP 写入失败")
			return
		}
		fmt.Printf("0602 TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", 1, 1, n, len(dataPart))
	} else {
		// 分帧处理
		if frameTail != 0 {
			frameQuantity++ // 最后一帧不满, 也算一帧
		}
		i := 1
		for i <= frameQuantity {
			respData[5] = byte(frameQuantity)
			respData[6] = byte(i)
			tmpData := make([]byte, 0)
			tmpData = append(tmpData, 0x5a, 0x06, cmdCode, 0xFF, 0xFF, byte(frameQuantity), byte(i))
			tmpData = append(tmpData, dataScaleBytes...)
			if i == frameQuantity {
				if frameTail == 0 {
					tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
				} else {
					tmpData = append(tmpData, dataPart[(i-1)*1200:(i-1)*1200+frameTail]...)
				}
			} else {
				tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
			}
			tmpData = append(tmpData, 0x00, 0x00, 0x00, 0x00, 0xa5)
			FixDataLength(tmpData)
			n, err = client.Connection.Write(tmpData)
			if err != nil {
				err = errors.New("0602 TCP 写入失败")
				return
			}
			fmt.Printf("0602 TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", frameQuantity, i, n, len(tmpData[17:len(tmpData)-5]))
			i++
			//time.Sleep(time.Millisecond * 10)
		}
	}
	return
}
func Response0603(fse *FSEquip, client *Client) (err error) {
	var n int
	respData, err := GenFSFrameData0603(fse)
	if err != nil {
		err = errors.New("pkg.GenFSFrameData0603 失败")
		return
	}
	cmdCode := respData[2]
	dataScaleBytes := respData[7:17]           // 数据规模部分
	dataPart := respData[17 : len(respData)-5] // 数据内容部分
	frameQuantity := len(dataPart) / 1200      // 数据内容分成几帧
	frameTail := len(dataPart) % 1200          // 余数
	fmt.Printf("数据部分总长度=%d\n", len(dataPart))
	//fmt.Printf("data=%s\n", tools.ByteArrayToHexStr(dataPart))
	if frameQuantity == 0 || (frameQuantity == 1 && frameTail == 0) {
		// 只有1帧的情况
		respData[5] = 1
		respData[6] = 1
		n, err = client.Connection.Write(respData)
		if err != nil {
			err = errors.New("0603 TCP 写入失")
			return
		}
		fmt.Printf("0603 TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", 1, 1, n, len(dataPart))
	} else {
		// 分帧处理
		if frameTail != 0 {
			frameQuantity++ // 最后一帧不满, 也算一帧
		}
		i := 1
		for i <= frameQuantity {
			respData[5] = byte(frameQuantity)
			respData[6] = byte(i)
			tmpData := make([]byte, 0)
			tmpData = append(tmpData, 0x5a, 0x06, cmdCode, 0xFF, 0xFF, byte(frameQuantity), byte(i))
			tmpData = append(tmpData, dataScaleBytes...)
			if i == frameQuantity {
				if frameTail == 0 {
					tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
				} else {
					tmpData = append(tmpData, dataPart[(i-1)*1200:(i-1)*1200+frameTail]...)
				}
			} else {
				tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
			}
			tmpData = append(tmpData, 0x00, 0x00, 0x00, 0x00, 0xa5)
			FixDataLength(tmpData)
			n, err = client.Connection.Write(tmpData)
			if err != nil {
				err = errors.New("0603 TCP 写入失败")
				return
			}
			fmt.Printf("0603 TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", frameQuantity, i, n, len(tmpData[17:len(tmpData)-5]))
			i++
			//time.Sleep(time.Millisecond * 10)
		}
	}
	return
}

func Response0604(fse *FSEquip, client *Client) (err error) {
	var n int
	respData, err := GenFSFrameData0604(fse)
	if err != nil {
		err = errors.New("pkg.GenFSFrameData0603 失败")
		return
	}
	cmdCode := respData[2]
	dataScaleBytes := respData[7:17]           // 数据规模部分
	dataPart := respData[17 : len(respData)-5] // 数据内容部分
	frameQuantity := len(dataPart) / 1200      // 数据内容分成几帧
	frameTail := len(dataPart) % 1200          // 余数
	fmt.Printf("数据部分总长度=%d\n", len(dataPart))
	//fmt.Printf("data=%s\n", tools.ByteArrayToHexStr(dataPart))
	if frameQuantity == 0 || (frameQuantity == 1 && frameTail == 0) {
		// 只有1帧的情况
		respData[5] = 1
		respData[6] = 1
		n, err = client.Connection.Write(respData)
		if err != nil {
			err = errors.New("0603 TCP 写入失")
			return
		}
		fmt.Printf("0604 TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", 1, 1, n, len(dataPart))
	} else {
		// 分帧处理
		if frameTail != 0 {
			frameQuantity++ // 最后一帧不满, 也算一帧
		}
		i := 1
		for i <= frameQuantity {
			respData[5] = byte(frameQuantity)
			respData[6] = byte(i)
			tmpData := make([]byte, 0)
			tmpData = append(tmpData, 0x5a, 0x06, cmdCode, 0xFF, 0xFF, byte(frameQuantity), byte(i))
			tmpData = append(tmpData, dataScaleBytes...)
			if i == frameQuantity {
				if frameTail == 0 {
					tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
				} else {
					tmpData = append(tmpData, dataPart[(i-1)*1200:(i-1)*1200+frameTail]...)
				}
			} else {
				tmpData = append(tmpData, dataPart[(i-1)*1200:i*1200]...)
			}
			tmpData = append(tmpData, 0x00, 0x00, 0x00, 0x00, 0xa5)
			FixDataLength(tmpData)
			n, err = client.Connection.Write(tmpData)
			if err != nil {
				err = errors.New("0604 TCP 写入失败")
				return
			}
			fmt.Printf("0604TCP写入成功 总帧数=%d,帧号=%d,当前帧长度=%d,数据部分长度=%d\n", frameQuantity, i, n, len(tmpData[17:len(tmpData)-5]))
			i++
			//time.Sleep(time.Millisecond * 10)
		}
	}
	return
}

func Response0684(fse *FSEquip, client *Client) (err error) {
	data := make([]byte, 0)
	data = append(data, 0x5a, 0x06, 0x84, 0xFF, 0xFF, 0x01, 0x01)
	data = append(data, fse.DS.AI, fse.DS.DI, fse.DS.AQ, fse.DS.DQ, fse.DS.Other)
	eDataBytes := tools.Uint16ToBytes(fse.DS.EData, "big")
	data = append(data, eDataBytes[:]...)
	data = append(data, fse.DS.Bengzu, fse.DS.Zengya, fse.DS.Pressure)

	data = append(data, 0x00)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xa5)
	data = append(data, 0x00, 0x00, 0x00, 0x00, 0xa5)
	FixDataLength(data)
	_, err = client.Connection.Write(data)
	if err != nil {
		err = errors.New("0684 TCP 写入失败")
		return
	}
	return
}

// ReceiveHandle0604 运行同步修改AIAQ值
func ReceiveHandle0604(fse *FSEquip, buffer []byte) (err error) {
	blockLength := buffer[17]
	fmt.Printf("blockLength=%d\n", blockLength)
	i := 18
	blockIndex := 0
	for blockIndex < int(blockLength) {
		blockType := buffer[i]
		i++
		addr := buffer[i]
		i++
		number := buffer[i]
		i++
		value := tools.BytesToFloat32(buffer[i:i+4], "big")
		i += 4
		code2 := ""                          // 模块,模型类型
		code3 := fmt.Sprintf("%02d", addr)   // 模块,模型序号
		code4 := fmt.Sprintf("%03d", number) // 通道号, 值序号
		key := ""
		switch blockType {
		case 0x00:
			code2 = "00"
			key = fmt.Sprintf("%s-%s-%s-%s", fse.Code1, code2, code3, code4)
		case 0x01:
			code2 = "01"
			key = fmt.Sprintf("%s-%s-%s-%s", fse.Code1, code2, code3, code4)
		case 0x02:
			code2 = "03"
			key = fmt.Sprintf("%s-%s-%s-%s", fse.Code1, code2, code3, code4)
		case 0x03:
			code2 = "04"
			key = fmt.Sprintf("%s-%s-%s-%s", fse.Code1, code2, code3, code4)
		case 0x04:
			code2 = "05"
			for _, module := range fse.FSModule {
				if module.Code1 == fse.Code1 && module.Code2 == code2 && module.Code3 == code3 {
					switch number {
					case 1:
						module.BengzuModel.BengzuStartControlValue = byte(value)
					case 2:
						module.BengzuModel.BengzuStopControlValue = byte(value)
					case 3:
						module.BengzuModel.LiansuoValue = byte(value)
					default:
						err = errors.New("泵组电磁阀值序号可选范围为[1,2,3]")
						return
					}
				}
			}
		case 0x05:
			code2 = "06"
			for _, module := range fse.FSModule {
				if module.Code1 == fse.Code1 && module.Code2 == code2 && module.Code3 == code3 {
					switch number {
					case 1:
						module.ZengyaModel.LiansuoValue = byte(value)
					default:
						err = errors.New("增压泵电磁阀值序号可选范围为[1]")
						return
					}
				}
			}
		case 0x06:
			code2 = "08"
			for _, module := range fse.FSModule {
				if module.Code1 == fse.Code1 && module.Code2 == code2 && module.Code3 == code3 {
					switch number {
					case 1:
						module.PressureSVModel.LiansuoValue = byte(value)
					default:
						err = errors.New("压力电磁阀值序号可选范围为[1]")
						return
					}
				}
			}
		default:
			err = errors.New(fmt.Sprintf("无效的参数blockType=%02d\n", blockType))
			return
		}
		if key != "" {
			err = fse.Set(key, float64(value))
			if err != nil {
				return
			}
		}
		blockIndex++
	}
	return
}

func (fse *FSEquip) Set(key string, v float64) (err error) {
	fmt.Printf("Set key=%s,value=%f\n", key, v)
	matchedAddr := false
	for _, module := range fse.FSModule {
		for _, item := range module.FrameItem {
			if item.Addr == key {
				matchedAddr = true
				item.Value = v
			}
		}
	}
	if !matchedAddr {
		err = errors.New(fmt.Sprintf("Set error 变量地址不存在, key=%s\n", key))
		return
	}
	return
}

func UpdateFSE(fse *FSEquip, fsm *FSModule) {
	matched := false
	fsm.ModuleType = Code2ToType[fsm.Code2]
	for _, module := range fse.FSModule {
		if module.Code1 == fsm.Code1 && module.Code2 == fsm.Code2 && module.Code3 == fsm.Code3 {
			module.FrameItem = fsm.FrameItem
			matched = true
			break
		}
	}
	if !matched {
		fse.FSModule = append(fse.FSModule, fsm)
	}
	fse.CalculateDataScale()
}

func OtherModuleType(n byte) (moduleType string) {
	switch n {
	case 0x01:
		moduleType = "AI"
	case 0x02:
		moduleType = "AQ"
	case 0x03:
		moduleType = "DI"
	case 0x04:
		moduleType = "DQ"
	}
	return
}
